package com.zzyl.framework.interceptor;

import cn.hutool.core.util.ObjectUtil;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.framework.web.service.TokenService;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Component
public class MemberInterceptor implements HandlerInterceptor {

    @Autowired
    private TokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断当前请求是否是handler()  [所有有@XXXMapping注解的方法  处理器]
        // instanceof 操作符用于检查对象是否属于特定类型
        if (!(handler instanceof HandlerMethod)){
            return true;
        }
        //1.获取请求头的token
        String token = request.getHeader("authorization");
        //2.token为空,则响应401(如果token为null,空字符串,且,解析的数据是空的,说明token无效或过期)
        if (ObjectUtil.isEmpty(token)|| tokenService.parseToken(token)==null){
            throw new BaseException("认证失败!");
        }
        //3.获取用户ID, userId
        //解析令牌
        Claims map = tokenService.parseToken(token);
        //获取令牌
        Long userId = map.get("userId", Long.class);
        //4.userId==null,响应401
        if (ObjectUtil.isEmpty(userId)){
            throw new BaseException("认证失败!");
        }
        //5.把userId存入ThreadLocal(UserThreadLocal)
        UserThreadLocal.set(userId);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserThreadLocal.remove();
    }
}
